import { ref, computed } from 'vue';

import { defineStore } from 'pinia';

import {
  getCityByIp,
  getAdcodeByCity,
  getWeatherByAdcode,
  getRealtimeWeatherByAdcode,
} from '@/api/index.js';

export const useWeatherStore = defineStore('weather', () => {
  //本地城市天气信息
  const city = ref(''); //本地城市
  const adcode = ref(''); //本地城市adcode
  const weatherForecasts = ref([]); //本地城市天气预报
  const currentWeather = ref([]); //本地城市实时天气
  const localDayTemperatures = ref([]); // 本地城市4天白天温度数据
  const localNightTemperatures = ref([]); // 本地城市4天晚上温度数据

  // 用户搜索城市天气信息
  const searchCity = ref(''); //用户搜索城市
  const searchCityAdcode = ref(''); //用户搜索城市adcode
  const searchCityWeatherForecasts = ref([]); //用户搜索城市天气预报
  const searchCityCurrentWeather = ref([]); //用户搜索城市实时天气
  const searchCityDayTemperatures = ref([]); // 搜索城市4天白天温度数据
  const searchCityNightTemperatures = ref([]); // 搜索城市4天晚上温度数据

  // 控制模态框的显示/隐藏
  const isModalVisible = ref(false);
  //控制模态框显示/隐藏的过渡效果
  const isModalVisibleTransition = ref(false);
  // 控制搜索页面'加号'的显示和隐藏
  const isSearchPageAddVisible = ref(false);

  //定义一个数据结构作为localStorage键值对的值
  const localStorageData = ref([]);

  // 获取星期几
  const getDayOfWeek = dateString => {
    const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const date = new Date(dateString);
    const dayOfWeekIndex = date.getDay();
    return daysOfWeek[dayOfWeekIndex];
  };

  // 保存天气预报数组中4天的温度数据
  const saveDailyTemperatures = (forecasts, dayTemps, nightTemps) => {
    dayTemps.value = forecasts.map(forecast => forecast.daytemp);
    nightTemps.value = forecasts.map(forecast => forecast.nighttemp);
  };

  //获取本地城市天气信息
  const getLocalWeather = async () => {
    try {
      //通过 ip 地址查询所在城市
      city.value = (await getCityByIp()).city;
      //通过城市名查询 adcode
      adcode.value = (await getAdcodeByCity(city.value)).geocodes[0].adcode;
      //通过 adcode 查询城市天气
      weatherForecasts.value = (await getWeatherByAdcode(adcode.value)).forecasts[0].casts;
      //通过 adcode 查询城市实时天气
      currentWeather.value = (await getRealtimeWeatherByAdcode(adcode.value)).lives[0];
      // 保存本地城市的温度数据
      saveDailyTemperatures(weatherForecasts.value, localDayTemperatures, localNightTemperatures);
    } catch (error) {
      console.error('获取天气数据时发生错误:', error);
    }
  };

  //获取搜索城市天气信息
  const getSearchCityWeather = async cityName => {
    try {
      searchCity.value = cityName;
      //通过城市名查询 adcode
      searchCityAdcode.value = (await getAdcodeByCity(searchCity.value)).geocodes[0].adcode;
      //通过 adcode 查询城市天气
      searchCityWeatherForecasts.value = (
        await getWeatherByAdcode(searchCityAdcode.value)
      ).forecasts[0].casts;
      //通过 adcode 查询城市实时天气
      searchCityCurrentWeather.value = (
        await getRealtimeWeatherByAdcode(searchCityAdcode.value)
      ).lives[0];
      // 保存搜索城市的温度数据
      saveDailyTemperatures(
        searchCityWeatherForecasts.value,
        searchCityDayTemperatures,
        searchCityNightTemperatures
      );
    } catch (error) {
      console.error('获取天气数据时发生错误:', error);
    }
  };

  // 计算4天的实时天气信息,获取需要的数据
  const computeDailyWeatherForecasts = forecasts => {
    if (!forecasts || forecasts.length === 0) return [];

    const now = new Date();
    const currentHour = now.getHours();
    const isDaytime = currentHour >= 8 && currentHour <= 20; // 假设白天为 8 点到 20 点

    return forecasts.map(item => {
      return isDaytime
        ? {
            date: item.date,
            weather: item.dayweather,
            windPower: item.daypower,
          }
        : {
            date: item.date,
            weather: item.nightweather,
            windPower: item.nightpower,
          };
    });
  };

  // 本地城市4天的实时天气信息
  const dailyWeatherForecasts = computed(() =>
    computeDailyWeatherForecasts(weatherForecasts.value)
  );

  // 搜索城市4天的实时天气信息
  const searchCityDailyWeatherForecasts = computed(() =>
    computeDailyWeatherForecasts(searchCityWeatherForecasts.value)
  );

  // 渲染echarts配置项
  const renderChartOption = (option, v1, v2) => {
    option.value = {
      xAxis: {
        type: 'category',
        show: false,
        boundaryGap: false,
        data: ['今天', '明天', '后天', '大后天'],
      },
      yAxis: {
        type: 'value',
        show: false,
        scale: true, // 启用缩放
      },
      grid: {
        top: '25%',
        bottom: '25%',
        left: '12%',
        right: '12%',
      },
      series: [
        {
          name: 'dayTemp',
          type: 'line',
          data: v1,
          smooth: true,
          itemStyle: {
            color: '#91cc75',
          },
          label: {
            show: true,
            position: 'top',
            color: '#fff',
            formatter: function (params) {
              return `白${params.value}℃`;
            },
          },
        },
        {
          name: 'nightTemp',
          type: 'line',
          data: v2,
          smooth: true,
          itemStyle: {
            color: '#5470c6',
          },
          label: {
            show: true,
            position: 'bottom',
            color: '#fff',
            formatter: function (params) {
              return `晚${params.value}℃`;
            },
          },
        },
      ],
    };
  };

  return {
    city,
    adcode,
    weatherForecasts,
    currentWeather,
    localDayTemperatures,
    localNightTemperatures,
    dailyWeatherForecasts,

    searchCity,
    searchCityAdcode,
    searchCityWeatherForecasts,
    searchCityCurrentWeather,
    searchCityDayTemperatures,
    searchCityNightTemperatures,
    searchCityDailyWeatherForecasts,

    isModalVisible,
    isModalVisibleTransition,
    isSearchPageAddVisible,
    localStorageData,

    getDayOfWeek,
    getLocalWeather,
    getSearchCityWeather,
    computeDailyWeatherForecasts,
    renderChartOption,
  };
});
